import React, { Component } from 'react';
import { connect } from 'react-redux';
import { messages } from 'share/common';
import AdvancedTable from 'components/advanced-table';
import constant from '../../finance-setting/loan-setting/constant';
import { Form, Radio, Input, Checkbox, Tabs, Popover, Button, message } from 'antd';
import checkCenterService from 'containers/financial-management/check-center/check-center.service';
import moment from 'moment';

const { TabPane } = Tabs;

const status = [{ '1001': messages('expense-16.key444')/*更新中*/ }, { '1002': messages('expense-16.key445')/*更新成功*/ }, { '1003': messages('expense-16.key446')/*更新失败*/ }];

@Form.create()
@connect(mapStateToProps)
class UpdateData extends Component {
  constructor(props) {
    super(props);

    this.state = {
      activeKey: 'update'
    };

    this.tabs = [
      {
        name: messages('expense-16.key443')/*数据更新*/,
        key: 'update',
        component: 'renderForm'
      },
      {
        name: messages('expense-16.key447')/*更新历史*/,
        key: 'history',
        component: 'renderHistory'
      }
    ];
  }

  static formMap = [
    {
      name: '',
      component: 'p',
      props: {},
      children: messages('expense-16.key448')/*已生成费用或已对账确认的数据无法进行更新*/,
      isNotFormList: true
    },
    {
      name: messages('expense-16.key449')/*更新维度*/,
      component: Radio,
      children: messages('expense-16.key86')/*批次号*/,
      props: {
        defaultChecked: true
      },
      extra: messages('expense-16.key450')/*目前仅携程支持按“批次号”更新数据*/,
      dataIndex: 'updateType' // 后端暂时没用到这个字段
    },
    {
      name: messages('expense-16.key86')/*批次号*/,
      component: Input,
      props: {
        placeholder: messages('common.please.input')/*请输入*/
      },
      dataIndex: 'checkBatchNo'
    },
    {
      name: messages('expense-16.key451')/*分发确认*/,
      component: Checkbox,
      children: messages('expense-16.key452')/*若数据有更新则重新分发*/,
      extra: messages('expense-16.key453')/*分发状态为已确认/逾期确认/反馈异常的数据，若有更新，则会重新分发给之前的确认人*/,
      dataIndex: 'dispenseFlag'
    }
  ];


  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  renderForm = () => {
    const { form: { getFieldDecorator } } = this.props;
    const { formItemLayout } = constant;
    return (
      <Form className="new-form">
        {
          UpdateData.formMap.map(item => {
            if (item.isNotFormList) return React.createElement(item.component, item.props, item.children);
            return (
              <Form.Item label={item.name} {...formItemLayout} extra={item.extra}>
                {getFieldDecorator(item.dataIndex)(React.createElement(item.component, item.props, item.children || null))}
              </Form.Item>
            );
          })
        }
        <section className="footer-operate">
          <Button key="back" onClick={this.handleCancel}>
            {messages('common.cancel')/*取消*/}
          </Button>,
          <Button
            key="sure"
            loading={this.state.updateLoading}
            type={'primary'}
            onClick={() => this.handleOk()}
          >
            {messages('common.ok')/*确定*/}
          </Button>
        </section>
      </Form>
    );
  };

  renderHistory = () => {
    const columns = [
      {
        title: messages('expense-16.key86')/*批次号*/,
        dataIndex: 'checkBatchNo',
        render: value => <Popover content={value}>{value}</Popover>
      },
      {
        title: messages('expense-16.key454')/*发起更新时间*/,
        dataIndex: 'updatedDate',
        render: value => (
          <Popover content={value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-'}>
            {value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-'}
          </Popover>)      },
      {
        title: messages('expense-16.key455')/*更新人*/,
        dataIndex: 'createdUserName',
        render: value => <Popover content={value}>{value}</Popover>
      },
      {
        title: messages('expense-16.key456')/*更新状态*/,
        dataIndex: 'status',
        render: value => (
          <Popover content={status.find(item => item[value])[value]}>
            {status.find(item => item[value])[value]}
          </Popover>
        )
      },
      {
        title: messages('common.operation')/*操作*/,
        dataIndex: 'operation',
        render: (value, record) => <div>{record.status === 1003 ? <a onClick={() =>this.reUpdate(record)}>{messages('expense-16.key457')/*重试*/}</a> : '-'}</div>
      }
    ];

    const searchForm = [{
      id: 'status',
      label: messages('common.column.status')/*状态*/,
      component: 'CheckboxGroup',
      dataIndex: 'status',
      props: {
        getPopupContainer: (triggerNode) => triggerNode.parentNode
      },
      parser: value => ({
        status: value && value[0]? value.map(item => item - '0') : void 0,
      }),
      children: status.map(value =>
        <Checkbox value={Object.getOwnPropertyNames(value)[0]}>
          {value[Object.getOwnPropertyNames(value)[0]]}
        </Checkbox>
      )
    }];
    return (
      <div className="reconciliation-update-data">
        <header
          className="reconciliation-update-data-padding">{messages('expense-16.key458')/*发起更新后，数据将在半小时左右更新完成，请稍候，处理完成后将给您发送提醒消息。\n          若由于网络原因或接口超时导致更新失败，请点击取消或者重试*/}
        </header>
        <AdvancedTable.SimpleTable
          className="reconciliation-update-data-padding"
          columns={columns}
          searchForm={searchForm}
          size={'small'}
          bordered
          onRef={ref => this.advancedTableRef = ref}
          service={this.service}
          rowKey={'id'}
        />
        <section className="footer-operate">
          <Button key="back" onClick={this.handleCancel}>
            {messages('expense-16.key459')/*关闭*/}
          </Button>,
        </section>
      </div>
    );
  };


  service = async (page, size, searchParams) => {
    const res = await checkCenterService.getReconciliationDataList({
      page,
      size,
      channel: 'hly-admin',
      ...searchParams
    });
    res.data.rows = res.data.settlementUpdateInfoDTOS;
    return res;
  };

  reUpdate = (record) => {
    this.handleOk(record);
  };

  handleOk = (record) => {
    this.props.form.validateFieldsAndScroll(async (err, values) => {
      const { checkBatchNo, dispenseFlag } = (record ? record : values);
      const { vendor = 'ctrip', vendorType } = (record ? record : this.props);
      const params = {
        checkBatchNo,
        dispenseFlag: !!dispenseFlag,
        vendor,
        vendorType,
        channel: 'hly-admin'
      };
      this.setState({ updateLoading: true });
      try {
        const res = await checkCenterService.updateReconciliationData(params);
        res.data.responseCode === '200'
          ? this.setState({ activeKey: 'history' }, () => setTimeout(this.advancedTableRef.getList, 300))
          : message.error(res.data.responseMessage);
      } catch (e) {}
      this.setState({ updateLoading: false });
    });
  };

  handleCancel = () => {
    this.props.onCancel();
  };

  handleTabChange = (tab) => {
    this.setState({ activeKey: tab });
  };

  render() {
    return (
      <Tabs defaultActiveKey="update" activeKey={this.state.activeKey} onChange={this.handleTabChange}>
        {
          this.tabs.map(item => React.createElement(TabPane, {
            tab: item.name,
            key: item.key,
            forceRender: false
          }, this[item.component]()))
        }
      </Tabs>
    );
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  };
}

UpdateData.propTypes = {};

export default UpdateData;
